package com.my.netty.optimize.client;

import com.my.netty.optimize.client.handler.RpcResponseMessageHandler;
import com.my.netty.optimize.message.RpcRequestMessage;
import com.my.netty.optimize.message.SequenceIdGenerator;
import com.my.netty.optimize.protocol.MessageCodecSharable;
import com.my.netty.optimize.protocol.ProtocolFrameDecoder;
import com.my.netty.optimize.server.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;

/**
 * 第二版rpc client
 */
@Slf4j
public class RpcClientManager {

    public static void main(String[] args) {
        //获取客户端代理对象
        HelloService helloService = RpcClientManager.getProxyService(HelloService.class);
        String res = helloService.sayHello("www");
        System.out.println(res);
        String res2 = helloService.sayHello("张三");
        System.out.println(res2);
        String res3 = helloService.sayHello("李四");
        System.out.println(res3);
    }

    private volatile static Channel channel;

    private static final Object LOCK = new Object();

    //获取唯一的channel对象
    public static Channel getChannel() {
        //单例模式初始化channel
        if (channel == null) {
            synchronized (LOCK) {
                if (channel == null) {
                    initChannel();
                }
            }
        }
        return channel;
    }

    //创建客户端service代理对象
    public static <T> T getProxyService(Class<T> clazz) {
        Object proxyInstance = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, (proxy, method, args) -> {
            //获取channel
            Channel channel = RpcClientManager.getChannel();
            //创建rpc请求消息对象
            int sequenceId = SequenceIdGenerator.nextId();
            RpcRequestMessage requestMessage = new RpcRequestMessage();
            requestMessage.setSequenceId(sequenceId);
            requestMessage.setInterfaceName(clazz.getName());
            requestMessage.setMethodName(method.getName());
            requestMessage.setParameterTypes(method.getParameterTypes());
            requestMessage.setParameterValue(args);
            requestMessage.setReturnType(method.getReturnType());
            //发送消息
            channel.writeAndFlush(requestMessage);

            //等待响应
            //创建一个空Promise，放到RpcResponseMessageHandler中；构造方法中指定异步接收promise结果的线程为当前channel的NIO线程(指执行addListener回调的线程，不是执行setSuccess/setFailure的线程)
            DefaultPromise<Object> promise = new DefaultPromise<>(channel.eventLoop());
            RpcResponseMessageHandler.PROMISES.put(sequenceId, promise);
            //让当前线程等待NIO线程放置promise的结果
            promise.await();
            //此时拿到结果
            if (promise.isSuccess()) {
                //拿到成功结果
                return promise.getNow();
            } else {
                //拿到异常结果
                throw new Exception(promise.cause());
            }
        });
        return (T) proxyInstance;
    }

    //初始化channel
    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable messageSharableCodec = new MessageCodecSharable();
        // PRC 请求消息处理器
        RpcResponseMessageHandler rpcResponseMessageHandler = new RpcResponseMessageHandler();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProtocolFrameDecoder());
                ch.pipeline().addLast(loggingHandler);
                ch.pipeline().addLast(messageSharableCodec);
                ch.pipeline().addLast(rpcResponseMessageHandler);
            }
        });
        try {
            //连接服务端
            channel = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync().channel();

            //channel关闭时关闭线程池
            channel.closeFuture().addListener((ChannelFutureListener) future ->
                    group.shutdownGracefully()
            );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
